import os
import urllib.request
from datetime import datetime
from time import time
from flask import current_app, jsonify, request
from app.ExportReport.ExportReport import ExportReport
from app.config.secure import PPYY_DIR, REPORT_DIR
from app.libs.error_code import Success
from app.libs.redprint import Redprint
from app.libs.tools import get_token
from app.models.captcha import captcha
from app.models.taobao_orders import taobao_orders
from app.models.base import db
from app.models.order_info import order_info
from app.models.orders import orders
from app.models.paragraphs import Paragraphs
from app.models.sentence import sentence
# from app.oss.alioss import AliOss
from app.validators.article import ArticleSubmitForm, ReportSearchForm, ShopForm, AutoDealForm
from app.view_models.OrderInfo import OrderInfolistView
from app import redisclient
from app import executor

api = Redprint('article')


@api.route("/submit", methods=['POST'])
def submit():
    form = ArticleSubmitForm().validate_for_api()
    currentTime = str(int(datetime.now().timestamp()))
    with db.auto_commit():
        submit_title = currentTime + '##' + form.title.data.replace(' ', '').replace('/', '').strip()
        submit_title = submit_title[0:20]
        if form.free.data == 1:
            order_number = '9' + str(round(time() * 1000))
        else:
            order_number = '8' + str(round(time() * 1000))
        order = orders()
        order.order_number = order_number
        order.content = form.content.data
        order.author = form.author.data
        order.char_sum = form.chars_sum.data
        order.title = form.title.data
        order.submit_title = submit_title
        db.session.add(order)
        for taobao_order in form.taobao_orders:
            info = order_info()
            info.taobao_orders = taobao_order
            info.order_number = order_number
            info.title = form.title.data
            info.chars_sum = form.chars_sum.data
            info.author = form.author.data
            info.submit_title = submit_title
            db.session.add(info)
        if form.free.data == 0:
            redisclient.push_paper(submit_title, form.author.data, form.content.data)
        else:
            redisclient.push_delaypaper(currentTime, submit_title, form.author.data, form.content.data)
    return Success()


@api.route('/search', methods=['POST'])
def search():
    form = ReportSearchForm().validate_for_api()
    view = OrderInfolistView()
    res = order_info.query.filter_by(taobao_orders=form.order_number.data).all()
    taobaoinfo = taobao_orders.query.filter_by(order_number=form.order_number.data).first()
    remain = taobaoinfo.remain if taobaoinfo else 0
    view.fill(res, remain)
    return jsonify(view)


@api.route('/check_unsubmit', methods=['GET'])
def check_unsubmit():
    now = int(time())
    unPapers = order_info.query.filter_by(completed=0).filter(order_info.create_time > now - 15 * 60).all()
    for item in unPapers:
        if now - item.create_time > 60 * 5 and item.order_number[0] == '8':
            paperInfo = orders.query.filter_by(submit_title=item.submit_title).first()
            redisclient.push_paper(paperInfo.submit_title, paperInfo.author, paperInfo.content)
    return Success()


@api.route('/shop', methods=['POST'])
def shop():
    form = ShopForm().validate_for_api()
    url = redisclient.getshop(form.domain.data)
    return jsonify({'shop': url})


@api.route('/checkreport', methods=['GET'])
def check():
    order_number = request.args['orname']
    report = captcha.query.filter(captcha.captcha_number == order_number).first()
    if report:
        res = {
            'msg': 0,
            'title': report.title,
            'yz': report.captcha_number,
            'zx': report.char_sum,
            'pe': report.similar_rate,
            'date': report.create_time
        }
    else:
        res = {
            'msg': 1
        }
    return jsonify(res)


# @api.route('/autodeal', methods=['POST'])
# def autodeal():
#     form = AutoDealForm().validate_for_api()
#     executor.submit(__make_report, form.reports.data, current_app._get_current_object())
#     return Success()


@api.route('/check', methods=['POST'])
def checkreport():
    form = AutoDealForm().validate_for_api()
    for report in form.reports.data:
        submit_title = report.split('$$')[0]
        status = report.split('$$')[2]
        orderInfo = order_info.query.filter_by(submit_title=submit_title).first()
        if orderInfo and orderInfo.completed != 1:
            if status == '已完成' and orderInfo.completed in [0, -2]:
                with db.auto_commit():
                    order_info.query.filter_by(submit_title=submit_title).update({
                        'completed': -1
                    })
                redisclient.push_report(report)
            if status == '待检测':
                with db.auto_commit():
                    order_info.query.filter_by(submit_title=submit_title).update({
                        'completed': -2
                    })
    return Success()


# def __make_report(reportList, app):
#     with app.app_context():
#         redisclient.set_MakeReport(0)
#         for report in reportList:
#             submit_title = report.split('$$')[0]
#             url = report.split('$$')[1]
#             orderInfo = order_info.query.filter_by(submit_title=submit_title).first()
#             if orderInfo and orderInfo.completed == 0:
#                 try:
#                     urllib.request.urlretrieve(url, PPYY_DIR + submit_title + '.zip')
#                     report_model = ExportReport(PPYY_DIR + submit_title + '.zip', orderInfo.order_number)
#                     report_model.create_report_directory()
#                     report_model.create_paper_html()
#                     for detail in report_model.details:
#                         report_model.create_index_html(str(detail['index']), detail['info'])
#                     info = orders.query.filter_by(order_number=orderInfo.order_number).first()
#                     rateStr = report_model.ppyy_model.Orianna()
#                     rate = round(float(rateStr.replace('%', '')), 2)
#                     if rate > 5:
#                         rate = round(rate * 0.95, 2)
#                     view_info = {
#                         'captcha': get_token(),
#                         'title': info.title,
#                         'author': info.author,
#                         'char_sum': len(info.content),
#                         'paragraphs': len(report_model.paragraphs),
#                         'submit_time': info.create_datetime,
#                         'rate': rate
#                     }
#                     with db.auto_commit():
#                         captcha_model = captcha()
#                         captcha_model.captcha_number = view_info['captcha']
#                         captcha_model.title = view_info['title']
#                         captcha_model.author = view_info['author']
#                         captcha_model.char_sum = view_info['char_sum']
#                         captcha_model.create_time = view_info['submit_time']
#                         captcha_model.similar_rate = view_info['rate']
#                         db.session.add(captcha_model)
#                         db.session.commit()
#                     if '\n' in info.content:
#                         text = info.content.split('\n')
#                         text_data = '<br>'.join(text)
#                     else:
#                         text_data = info.content
#                     report_model.create_report_html(view_info)
#                     report_model.create_orginal_html(text_data)
#                     report_model.create_pdf_html(view_info)
#                     report_model.zip_report()
#                     # oss = AliOss(orderInfo.order_number)
#                     oss.upload(REPORT_DIR + 'samereport_' + orderInfo.order_number + '.zip')
#                     with db.auto_commit():
#                         order_info.query.filter_by(order_number=orderInfo.order_number).update(
#                             {'completed': 1, 'similar_rate': rate})
#                     os.remove(REPORT_DIR + "samereport_" + orderInfo.order_number + '.zip')
#                 except Exception as e:
#                     with open('ReportError/' + submit_title + '.log', 'a') as f:
#                         f.write(str(e))
#         redisclient.set_MakeReport(1)


def __db_operation(sentences, content, order_number, app):
    with app.app_context():
        with db.auto_commit():
            paragraph_model = Paragraphs()
            sentence_model = sentence()
            paragraph_model.insert_paragrahs(content, order_number)
            sentence_model.insert_sentences(sentences, order_number)
            redisclient.setData(sentences, order_number)
            redisclient.push_task('task', order_number)
        print('save data complete!')
